package com.dcits.business.server.dubbo;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcits.business.server.BaseServerController;
import com.dcits.business.userconfig.UserSpace;
import com.dcits.tool.StringUtils;

public class DubboServerController extends BaseServerController {
	
	private static final Logger logger = Logger.getLogger(DubboServerController.class);
	
	public void breakCommand (){
		renderSuccess(null, "成功发送停止命令!");
	}
	
	public void execCommand() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		String ids = getPara("viewIds");
		final String command = getPara("command");
			
		final JSONArray returnArr = new JSONArray();
		
		for (String id:ids.split(",")) {
			final DubboServer server = (DubboServer) space.getServerInfo(DubboServer.SERVER_TYPE_NAME, Integer.valueOf(id));
			final JSONObject obj = new JSONObject();
			obj.put("useTime", 0);
			
			if (server == null) continue;
			
			obj.put("host", (StringUtils.isEmpty(server.getRealHost()) ? server.getHost() : server.getRealHost()) + "[" + server.getTags() + "]");
			Thread t = new Thread(new Runnable() {				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						long begin = System.currentTimeMillis();
						String returnInfo = server.request(command);
						long end = System.currentTimeMillis();
						obj.put("returnInfo", returnInfo.replace("dubbo>", ""));
						obj.put("useTime", (end - begin));
					} catch (Exception e) {
						// TODO: handle exception
						logger.error(obj.get("host").toString() + " 命令执行失败:" + command, e);
						obj.put("returnInfo", "命令执行失败:" + e.getMessage());						
					}
					returnArr.add(obj);
				}
			});
			t.start();
			try {
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		renderSuccess(returnArr, "命令执行成功!");
	}
}
